<template>
	<view class="addtopic-container">
		
		<unisection title="添加话题" type="line">
			
			<uni-forms :rules="rules" ref="form" :modelValue="formData">
				<uni-forms-item label="选择图片" name="imgs" required>
					<uni-file-picker v-model="formData.imgs" limit="2" :autoUpload="false"></uni-file-picker>
				</uni-forms-item>
				
				<uni-forms-item label="话题内容" name="content" required>
					<uni-easyinput v-model="formData.content" type="textarea" placeholder="请输入话题"></uni-easyinput>
				</uni-forms-item>
			</uni-forms>
			
		</unisection>
		
		<button type="primary" @click="submit">提交</button>
		
	</view>
</template>

<script>
	import unisection from '../../components/uni-section/uni-section.vue'
	const db = uniCloud.database()
	
	export default {
		name: 'addtopic',
		data() {
			return {
				formData: {
					imgs: [],
					content: ''
				},
				rules: {
					imgs: {
						rules: [
							{
								required: true,
								errorMessage: '请至少选择一张图片'
							}
						]
					},
					content: {
						rules: [
							{
								required: true,
								errorMessage: '话题不能为空'
							}
						]
					}
				}
			}
		},
		methods: {
			async sendpost() {
				const date = new Date().toLocaleString()
				console.log(this.formData)
				await db.collection('topic').add({
					content: this.formData.content,
					img_url: this.formData.imgs[0].fileID,
					likestatus: 0,
					likecount: 0,
					publish_time: date
				})
				uni.showToast({
					title: '帖子发布成功'
				})
			},
			async submit() {
				let res = await this.$refs.form.validate()
				console.log(res)
				this.formData = res
				let filename = this.formData.imgs[0].name.split('.')[0] + Math.floor(Math.random()*1000) + '.' + this.formData.imgs[0].extname
				uniCloud.uploadFile({
					filePath: this.formData.imgs[0].path,
					cloudPath: filename,
					success: res => {
						this.formData.imgs[0].fileID = res.fileID
						console.log(this.formData.imgs[0].fileID)
						this.sendpost()
					}
				})
			}
		},
		components: {
			unisection
		}
	}
</script>

<style lang="scss" scoped>
	page {
		width: 100%;
		height: 100%;
	}
	.addtopic-container {
		height: 100%;
	}
</style>